<template>
  <div class="admin">
    <div
      class="table-head-container d-flex justify-content-between align-items-center"
      :class="{ 'table-head-container-new': tableClass }"
    >
      <flexbox class="th-container">
        <div class="table-option-view">
          <template v-for="(item, index) in getSelectionHandleItemsInfo()">
            <div
              class="d-flex align-items-center"
              v-if="item.name"
              :key="index"
            >
              <div class="ml-16" style="text-wrap: nowrap">
                {{ item.name }}：
              </div>
              <!-- 渠道名称 -->
              <el-select
                v-model="queryOptions.name"
                :placeholder="placeholder"
                clearable
                :key="index"
                v-if="item.type == 'RoiName'"
                style="width: 120px"
                @change="nameChange"
              >
                <el-option
                  :value="item"
                  v-for="(item, index) in companyList"
                  :key="index"
                ></el-option>
              </el-select>
              <!-- 消耗日期 -->
              <el-date-picker
                v-if="item.type == 'consumeDate'"
                v-model="queryOptions.date"
                type="daterange"
                :default-time="['00:00:00', '23:59:59']"
                value-format="yyyy-MM-dd"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                @change="dateValChange"
                :picker-options="pickerOptions"
              >
              </el-date-picker>
              <!-- 部门 -->
              <manage-dep
                :key="index"
                class="mr-10"
                v-if="item.type == 'manage'"
                style="width: 120px;overflow: hidden;"
                @submitDeps="manageDepSave($event, 'queryOptions')"
                :manageDeptId="queryOptions.deptId"
                :showIpt="true"
                :visible="false"
                :isShowName="true"
              />
              <!-- 月份 -->
              <el-date-picker
                v-if="item.type == 'month'"
                v-model="queryOptions.month"
                type="month"
                placeholder="请选择"
                @change="monthChange"
                value-format="yyyy-MM"
              >
              </el-date-picker>
              <!-- 年份 -->
              <el-date-picker
                v-if="item.type == 'year'"
                v-model="queryOptions.year"
                type="year"
                placeholder="请选择"
                value-format="yyyy"
              >
              </el-date-picker>
            </div>
          </template>
          <el-button
            type="primary"
            @click="searchInput"
            icon="el-icon-search"
            style="margin-left: 16px"
            >搜索</el-button
          >

          <el-button
            v-if="mainTitle"
            type="primary"
            class="create-btn"
            icon="el-icon-plus"
            @click="createClick"
            >{{ mainTitle }}</el-button
          >
        </div>
      </flexbox>
    </div>
  </div>
</template>

<script>
import manageDep from "@/views/crm/workbench/components/manageDep"; // 部门选择器
import { querySourceAPI } from "@/api/roi";

export default {
  name: "CRMHead",
  components: {
    manageDep
    // newDialog
  },
  props: {
    title: {
      type: String,
      default: ""
    },
    mainTitle: {
      type: String,
      default: ""
    },
    crmType: {
      type: String,
      default: ""
    },
    placeholder: {
      type: String,
      default: "请输入内容"
    },
    tableClass: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      loading: false, // loading
      loadingObj: null, // loading 对象
      queryOptions: {
        name: "", //渠道名称
        inputContent: "",
        date: [], //日期
        deptId: [], // 部门id
        month: "",
        year: null
      },
      companyList: [],

      pickerMinDate: "",
      pickerOptions: {
        onPick: ({ maxDate, minDate }) => {
          this.pickerMinDate = minDate.getTime();
          if (maxDate) this.pickerMinDate = "";
        },
        disabledDate: time => {
          if (this.pickerMinDate !== "") {
            const one = 60 * 24 * 3600 * 1000;
            const minTime = this.pickerMinDate - one;
            const maxTime = this.pickerMinDate + one;
            return time.getTime() < minTime || time.getTime() > maxTime;
          }
        }
      }
    };
  },
  computed: {},
  watch: {
    loading(val) {
      if (val) {
        this.loadingObj = Loading.service({
          target: document.querySelector("#crm-main-container")
        });
      } else {
        this.loadingObj && this.loadingObj.close();
      }
    }
  },
  mounted() {
    this.getSource();
    this.getDate();
  },
  methods: {
    getDate() {
      const lastYearMonth = this.getLastMonth();
      const startTime = this.$moment(lastYearMonth).format("YYYY-MM") + "-01";
      const endTime = this.$moment(
        new Date(lastYearMonth.split("-")[0], lastYearMonth.split("-")[1], 0)
      ).format("YYYY-MM-DD");
      this.queryOptions.date = [startTime, endTime];
      this.$emit("date", this.queryOptions);
    },
    getLastMonth() {
      let date = new Date();
      let year = date.getFullYear(); //当前年：四位数字
      let month = date.getMonth(); //当前月：0-11
      if (month == 0) {
        //如果是0，则说明是1月份，上一个月就是去年的12月
        year -= 1;
        month = 12;
      }
      month = month < 10 ? "0" + month : month; //月份格式化：月份小于10则追加个0
      let lastYearMonth = year + "-" + month;
      return lastYearMonth;
    },

    showContTips() {
      this.showContractTip = Date.now();
    },
    // 新建消耗
    createClick() {
      this.$emit("handle", "1");
    },
    // 渠道名称
    nameChange() {
      this.$emit("name", this.queryOptions);
    },
    dateValChange() {
      this.$emit("date", this.queryOptions);
    },
    // 新加的
    inputChange() {
      this.$emit("update:search", this.queryOptions);
    },
    searchInput() {
      this.$emit("on-search", this.queryOptions);
    },
    monthChange() {
      this.$emit("monthchange", this.queryOptions);
    },
    manageDepSave(e, name) {
      this[name].deptId = e.split(",")[0] === "" ? [] : e.split(",");
    },
    /** 获取展示items */
    getSelectionHandleItemsInfo() {
      const handleInfos = {
        RoiName: {
          name: "渠道名称",
          type: "RoiName"
        },
        consumeDate: {
          name: "消耗日期",
          type: "consumeDate"
        },
        manage: {
          name: "部门",
          type: "manage"
        },
        month: {
          name: "选择月份",
          type: "month"
        },
        year: {
          name: "选择年份",
          type: "year"
        }
      };
      // ROI消耗
      if (this.crmType === "consume" || this.crmType === "consumeDept") {
        return this.forSelectionHandleItems(handleInfos, [
          "RoiName",
          "consumeDate",
          "manage"
        ]);
      } else if (this.crmType === "channel") {
        return this.forSelectionHandleItems(handleInfos, [
          "RoiName",
          "consumeDate",
          "manage"
        ]);
      } else if (this.crmType === "monthStatis") {
        return this.forSelectionHandleItems(handleInfos, ["month", "RoiName"]);
      } else if (this.crmType === "yearStatis") {
        return this.forSelectionHandleItems(handleInfos, ["RoiName"]);
      } else if (this.crmType === "groupAllStatis") {
        return this.forSelectionHandleItems(handleInfos, ["RoiName"]);
      }
    },

    forSelectionHandleItems(handleInfos, array) {
      const tempsHandles = [];
      for (let index = 0; index < array.length; index++) {
        tempsHandles.push(handleInfos[array[index]]);
      }
      return tempsHandles;
    },
    // 获取渠道列表
    getSource() {
      querySourceAPI()
        .then(res => {
          this.companyList = res.data;
        })
        .catch(() => {});
    },

    clearForm() {
      this.queryOptions.name = "";
      this.queryOptions.month = "";
    }
  }
};
</script>
<style lang="scss" scoped>
.table-head-container {
  padding: 14px 16px;
  background: white;
  margin: 0;
}
.table-head-container-new {
  padding: 14px 0;
  margin-left: -16px;
}
.th-container {
  font-size: 14px;
  .scene-select {
    width: 180px;

    /deep/ .el-input__inner {
      cursor: pointer;
    }
  }

  .filter-button {
    /deep/ i {
      font-size: 14px;
      margin-right: 5px;
    }
  }
}

/deep/ .el-date-editor .el-range__icon {
  line-height: 26px;
}
/deep/ .el-date-editor .el-range-separator {
  line-height: 26px;
}
.table-option-view {
  display: flex;
  align-items: center;
}
.create-btn {
  background: #07bf50;
  border-color: #07bf50;
  border-radius: 4px;
  color: #fff;
}
.ml-16 {
  margin-left: 16px;
}
.mr-16 {
  margin-right: 16px;
}
</style>
